package com.chenhy.tcp_tester;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * Create By HauyuChen
 * Email：Hauyu.Chen@gmail.com
 */

/* 客户端界面代码 */
public class ClientActivity extends Activity {
    private final String TAG = "ClientActivity";
    private EditText edit_ip;
    private EditText edit_port;
    private EditText edit_send;
    private EditText edit_recv;
    private Button btn_connect;
    private Button btn_send;
    private boolean isConnected = false;
    Socket socket = null;
    OutputStream writer = null;
    InputStream reader = null;
    private String line;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client);
        /* 初始化 */
        edit_ip = (EditText) findViewById(R.id.edit_ip);
        edit_port = (EditText) findViewById(R.id.edit_port);
        edit_send = (EditText) findViewById((R.id.edit_msgsend));
        edit_recv = (EditText) findViewById(R.id.edit_recv);
        btn_connect = (Button) findViewById(R.id.btn_connect);
        btn_send = (Button) findViewById(R.id.btn_send);
        /* 连接按钮 */
        btn_connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /* 连接按钮处理函数 */
                connect();
            }
        });
        /* 发送按钮 */
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /* 发送按钮处理函数 */
                send();
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            edit_recv.setText(line);
        }
    };

    /* 连接按钮处理函数：建立Socket连接 */
    @SuppressLint("HandlerLeak")
    public void connect() {
        if (!isConnected) {
            new Thread() {
                public void run() {
                    String IPAdr = edit_ip.getText().toString();
                    int PORT = Integer.parseInt(edit_port.getText().toString());
                    try {
                        socket = new Socket(IPAdr, PORT);
                        writer = socket.getOutputStream();

                        Log.i(TAG, "开始检测数据");
                        byte[] data = new byte[30];
                        while (true) {
                            reader = socket.getInputStream();
                            reader.read(data);
                            line = byte2HexString(data);
                            Log.i(TAG, "data:" + byte2HexString(data));

                            Message msg = handler.obtainMessage();
                            msg.obj = line;
                            handler.sendMessage(msg);
                            Log.i(TAG, "send to handler");

//                            if (data == new byte[30]){
//                                Looper.prepare();
//                                Toast.makeText(ClientActivity.this, "已断开连接：）", Toast.LENGTH_SHORT).show();
//                                Looper.loop();
//                                return;
//                            }
//
//                            //用来判断是否已断开连接
//                            data = new byte[30];
                        }

                    } catch (UnknownHostException e) {
                        Looper.prepare();
                        Toast.makeText(ClientActivity.this, "无法建立连接1：）", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                        e.printStackTrace();
                        isConnected = false;
                    } catch (IOException e) {
                        Looper.prepare();
                        Toast.makeText(ClientActivity.this, "无法建立连接2：）", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                        e.printStackTrace();
                        isConnected = false;
                    }
                }
            }.start();
            isConnected = true;
            //更新UI
            btn_connect.setText("断开");
            edit_recv.setText("");
            Toast.makeText(ClientActivity.this, "连接成功：）", Toast.LENGTH_SHORT).show();
        } else {
            isConnected = false;
            try {
                //关闭socket
                if (null != socket) {
                    socket.shutdownInput();
                    socket.shutdownOutput();
                    socket.getInputStream().close();
                    socket.getOutputStream().close();
                    socket.close();
                }
            } catch (IOException e) {
                Log.d(TAG, e.getMessage());
            }
            //更新UI
            btn_connect.setText("连接");
            edit_recv.setText("");
            Toast.makeText(ClientActivity.this, "连接已断开：）", Toast.LENGTH_SHORT).show();
        }
    }


    /* 发送按钮处理函数：向输出流写数据 */
    public void send() {
        try {
            String str = edit_send.getText().toString().trim();
            if (!str.isEmpty()) {
                writer.write(hexString2ByteArray(str));
                writer.flush();
            }
            edit_send.setText("");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            Log.e(TAG, e.toString());
        }
    }

    @Override
    protected void onDestroy() {
        try {
            /* 关闭socket */
            if (null != socket) {
                socket.shutdownInput();
                socket.shutdownOutput();
                socket.getInputStream().close();
                socket.getOutputStream().close();
                socket.close();
            }
        } catch (IOException e) {
            Log.d(TAG, e.getMessage());
        }
        /* 更新UI */
        btn_connect.setText("连接");
        edit_recv.setText("");
        super.onDestroy();
    }


    /**
     * To byte array byte [ ].
     *
     * @param hexString the hex string
     * @return the byte [ ]
     */
    public static byte[] hexString2ByteArray(String hexString) {
        try {
            if (hexString.isEmpty())
                return null;
            hexString = hexString.toLowerCase();
            final byte[] byteArray = new byte[hexString.length() >> 1];
            int index = 0;
            for (int i = 0; i < hexString.length(); i++) {
                if (index > hexString.length() - 1)
                    return byteArray;
                byte highDit = (byte) (Character.digit(hexString.charAt(index), 16) & 0xFF);
                byte lowDit = (byte) (Character.digit(hexString.charAt(index + 1), 16) & 0xFF);
                byteArray[i] = (byte) (highDit << 4 | lowDit);
                index += 2;
            }
            return byteArray;
        } catch (Exception e) {
            Log.e("hexString2ByteArray", e.toString());
            return null;
        }
    }

    /**
     * byte[] to Hex string.
     *
     * @param byteArray the byte array
     * @return the string
     */

    public static String byte2HexString(byte[] byteArray) {
        final StringBuilder hexString = new StringBuilder("");
        if (byteArray == null || byteArray.length <= 0)
            return null;
        for (int i = 0; i < byteArray.length; i++) {
            int v = byteArray[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                hexString.append(0);
            }
            hexString.append(hv);
        }
        return hexString.toString().toLowerCase();
    }
}
